#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <cstdlib>
#include <unistd.h>

#include "log.hpp"

static const int g_num = 1024;

void serviceIO(int sockfd)
{
    char buffer[g_num];
    while (true)
    {
        // a. 接收
        // ssize_t read(int fd, void *buf, size_t count);
        ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0; // 字符串
            std::cout << "receive message: " << buffer << std::endl;

            std::string outBuffer = buffer;
            outBuffer += " [server echo]";

            // b. 回送
            // ssize_t write(int fd, const void *buf, size_t count);
            write(sockfd, outBuffer.c_str(), outBuffer.size()); // 多路转接再考虑write返回值问题
        }
        else if (n == 0)
        {
            // 走到这里，代表Client exit
            logMessage(NORMAL, "client exit, me too");
            break;
        }
    }
    // version 4
    close(sockfd);
}

class Task
{
    using func_t = std::function<void(int)>;

public:
    Task() {}
    Task(const int sockfd, func_t func) : _sockfd(sockfd), _func(func)
    {
    }
    void operator()()
    {
        _func(_sockfd);
    }
    ~Task()
    {
    }

private:
    int _sockfd;
    func_t _func;
};
